package common

import (
	"flag"
	"fmt"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"log"
	"time"
)

var (
	SYS_DB          *gorm.DB
	SYS_CONFIG      Config
	Config_filename string
)

//从yaml解析配置文件
func init() {
	flag.StringVar(&Config_filename, "config", "config_company", "set config file name ")
	flag.Parse()
	var v = viper.New()
	v.SetConfigName(Config_filename)
	v.SetConfigType("yaml")
	v.AddConfigPath(".")
	err := v.ReadInConfig()
	if err != nil {
		panic(fmt.Errorf("Fatal error config file: %s \n", err))
	}
	if err := v.Unmarshal(&SYS_CONFIG); err != nil {
		fmt.Println("error:", err)
	}
}

//初始化mysql
func InitMysql() {
	var admin = SYS_CONFIG.Mysql
	var dsn = admin.Username + ":" + admin.Password + "@(" + admin.Path + ")/" + admin.Dbname + "?" + admin.Config
	var ormConfig = &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   admin.TablePrefix,   // 表名前缀，`User` 的表名应该是 `yk_users`
			SingularTable: admin.SingularTable, // 使用单数表名，启用该选项，此时，`User` 的表名应该是 `yk_user
		},
	}

	if db, err := gorm.Open(mysql.Open(dsn), ormConfig); err != nil {
		log.Fatal("MySQL启动异常,请详细检查配置参数")
	} else {
		SYS_DB = db
		mysqlDb, err := SYS_DB.DB()
		if err != nil {
			panic(err)
		}
		mysqlDb.SetMaxIdleConns(admin.MaxIdleConns)
		mysqlDb.SetMaxOpenConns(admin.MaxOpenConns)
		mysqlDb.SetConnMaxLifetime(time.Hour)
	}
}
